<template>
  <div>
    <!-- 面包屑导航 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/welcome' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>权限管理</el-breadcrumb-item>
      <el-breadcrumb-item>角色列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片视图 -->
    <el-card class="box-card">
      <!-- 添加角色按钮 -->
      <el-row>
        <el-col>
          <el-button type="primary" @click="addRolesDialogVisible = true"
            >添加角色</el-button
          >
        </el-col>
      </el-row>
      <!-- 角色列表 -->
      <el-table :data="rolesList" border stripe>
        <!-- 扩展列 -->
        <el-table-column type="expand">
          <template slot-scope="scope">
            <el-row
              :class="['bborder', index1 === 0 ? 'tborder' : '', 'vcenter']"
              v-for="(item1, index1) in scope.row.children"
              :key="item1.id"
            >
              <!-- 一级权限 -->
              <el-col :span="5">
                <el-tag
                  closable
                  @close="removeRightsById(scope.row, item1.id)"
                  >{{ item1.authName }}</el-tag
                >
                <i class="el-icon-caret-right"></i>
              </el-col>
              <!-- 二级和三级权限 -->
              <el-col :span="19">
                <el-row
                  :class="[index2 === 0 ? '' : 'tborder', 'vcenter']"
                  v-for="(item2, index2) in item1.children"
                  :key="item2.id"
                >
                  <!-- 二级权限 -->
                  <el-col :span="6">
                    <el-tag
                      type="success"
                      closable
                      @close="removeRightsById(scope.row, item2.id)"
                      >{{ item2.authName }}</el-tag
                    >
                    <i class="el-icon-caret-right"></i>
                  </el-col>
                  <!-- 三级权限 -->
                  <el-col :span="13">
                    <el-tag
                      type="warning"
                      v-for="item3 in item2.children"
                      :key="item3.id"
                      closable
                      @close="removeRightsById(scope.row, item3.id)"
                      >{{ item3.authName }}</el-tag
                    >
                  </el-col>
                </el-row>
              </el-col>
            </el-row>
          </template>
        </el-table-column>
        <!-- 索引列 -->
        <el-table-column type="index" label="序号"></el-table-column>
        <el-table-column prop="roleName" label="角色名称"></el-table-column>
        <el-table-column prop="roleDesc" label="角色描述"></el-table-column>
        <el-table-column label="操作" width="300px">
          <template slot-scope="scope">
            <el-button
              size="mini"
              type="primary"
              icon="el-icon-edit"
              @click="editRolesVis(scope.row.id)"
              >编辑</el-button
            >
            <el-button
              size="mini"
              type="danger"
              icon="el-icon-delete"
              @click="deleteRole(scope.row.id)"
              >删除</el-button
            >
            <el-button
              size="mini"
              type="warning"
              icon="el-icon-setting"
              @click="setRightsDialog(scope.row)"
              >分配权限</el-button
            >
          </template>
        </el-table-column>
      </el-table>
    </el-card>
    <!-- 添加角色弹窗 -->
    <el-dialog
      title="添加角色"
      :visible.sync="addRolesDialogVisible"
      width="50%"
      @close="addRolesDialogClosed"
    >
      <!-- 对话框主体区域 -->
      <el-form
        :model="addRolesForm"
        :rules="RolesFormRules"
        ref="addRolesFormRef"
        label-width="70px"
      >
        <el-form-item label="角色名称" prop="roleName" label-width="100px">
          <el-input v-model="addRolesForm.roleName"></el-input>
        </el-form-item>
        <el-form-item label="角色描述" prop="roleDesc" label-width="100px">
          <el-input v-model="addRolesForm.roleDesc"></el-input>
        </el-form-item>
      </el-form>
      <!-- 对话框底部 -->
      <span slot="footer" class="dialog-footer">
        <el-button @click="addRolesDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addRoles">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 编辑角色弹窗 -->
    <el-dialog
      title="编辑角色"
      :visible.sync="editRolesDialogVisible"
      width="50%"
      @close="editRolesDialogClosed"
    >
      <!-- 对话框主体区域 -->
      <el-form
        :model="editRolesForm"
        :rules="RolesFormRules"
        ref="editRolesFormRef"
        label-width="70px"
      >
        <el-form-item label="角色名称" prop="roleName" label-width="100px">
          <el-input v-model="editRolesForm.roleName"></el-input>
        </el-form-item>
        <el-form-item label="角色描述" prop="roleDesc" label-width="100px">
          <el-input v-model="editRolesForm.roleDesc"></el-input>
        </el-form-item>
      </el-form>
      <!-- 对话框底部 -->
      <span slot="footer" class="dialog-footer">
        <el-button @click="editRolesDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="editRoles">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 分配权限弹窗 -->
    <el-dialog
      title="设置权限"
      :visible.sync="setRightsDialogVisible"
      width="50%"
      @close="setRightsDialogClosed"
    >
      <!-- 对话框主体区域 -->
      <el-tree
        :data="rightsList"
        :props="rightsProps"
        show-checkbox
        node-key="id"
        default-expand-all
        :default-checked-keys="defKeys"
        ref="allotRef"
      ></el-tree>
      <!-- 对话框底部 -->
      <span slot="footer" class="dialog-footer">
        <el-button @click="setRightsDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="allotRights">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data() {
    return {
      // 角色列表
      rolesList: null,
      // 权限列表
      rightsList: null,
      // 权限树形控件属性
      rightsProps: {
        children: 'children',
        label: 'authName'
      },
      // 添加角色弹窗可见
      addRolesDialogVisible: false,
      // 编辑角色弹窗可见
      editRolesDialogVisible: false,
      // 设置权限弹窗可见
      setRightsDialogVisible: false,
      // 默认勾选权限的id
      defKeys: [],
      // 添加角色表单数据
      addRolesForm: {
        roleName: '',
        roleDesc: ''
      },
      // 编辑角色表单数据
      editRolesForm: {
        roleId: '',
        roleName: '',
        roleDesc: ''
      },
      // 角色表单验证规则
      RolesFormRules: {
        roleName: [
          { required: true, message: '请输入角色名称', trigger: 'blur' },
          {
            min: 2,
            max: 10,
            message: '角色在2~10个字符之间',
            trigger: 'blur'
          }
        ]
      },
      // 分配权限是当前角色的id
      currentAllotId: null
    }
  },
  created() {
    this.getRolesList()
  },
  methods: {
    // 获取角色列表
    async getRolesList() {
      const { data: res } = await this.$http.get('/roles')
      if (res.meta.status !== 200) {
        return this.$message.error('获取角色列表失败')
      }
      this.rolesList = res.data
    },
    // 添加角色
    addRoles() {
      // 预先验证表单数据
      this.$refs.addRolesFormRef.validate(async (valid) => {
        if (!valid) {
          return this.$message.error('请完整填写角色添加表单')
        }
        // 发起请求
        const { data: res } = await this.$http.post('/roles', this.addRolesForm)
        if (res.meta.status !== 201) {
          return this.$message.error('添加角色失败')
        }
        this.$message.success('添加角色成功')
        // 关闭弹窗
        this.addRolesDialogVisible = false
        // 重新渲染角色列表
        this.getRolesList()
      })
    },
    // 关闭弹窗后情况，角色添加数据清空
    addRolesDialogClosed() {
      this.$refs.addRolesFormRef.resetFields()
    },
    // 展示编辑弹框，查重数据展示
    async editRolesVis(id) {
      const { data: res } = await this.$http.get('roles/' + id)
      if (res.meta.status !== 200) {
        return this.$message.error('查询角色信息失败')
      }
      this.editRolesForm = res.data
      this.editRolesDialogVisible = true
      console.log(this.editRolesForm)
    },
    // 编辑角色
    editRoles() {
      // 预先验证表单数据
      this.$refs.editRolesFormRef.validate(async (valid) => {
        if (!valid) {
          return this.$message.error('请完整填写角色添加表单')
        }
        // 发起请求
        const { data: res } = await this.$http.put(
          '/roles/' + this.editRolesForm.roleId,
          {
            roleDesc: this.editRolesForm.roleDesc,
            roleName: this.editRolesForm.roleName
          }
        )
        if (res.meta.status !== 200) {
          return this.$message.error('修改角色失败')
        }
        this.$message.success('修改角色成功')
        // 关闭弹窗
        this.editRolesDialogVisible = false
        // 重新渲染角色列表
        this.getRolesList()
      })
    },
    // 关闭弹窗后情况，角色编辑数据清空
    editRolesDialogClosed() {
      this.$refs.editRolesFormRef.resetFields()
    },
    // 删除角色
    deleteRole(id) {
      this.$confirm('此操作将永久删除该角色, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(async () => {
          const { data: res } = await this.$http.delete(
            `/roles/${parseInt(id)}`
          )
          if (res.meta.status !== 200) {
            return this.$message.error('删除角色失败')
          }
          this.$message({
            type: 'success',
            message: '删除角色成功!'
          })
          this.getRolesList()
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          })
        })
    },
    // 删除对应id权限
    removeRightsById(role, rightid) {
      // 删除弹框
      this.$confirm('此操作将永久删除该权限, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(async () => {
          const { data: res } = await this.$http.delete(
            `roles/${role.id}/rights/${rightid}`
          )
          if (res.meta.status !== 200) {
            return this.$message.error('删除用户权限失败')
          }
          this.$message.success('成功删除用户权限')
          role.children = res.data
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          })
        })
    },
    // 展示所有权限
    async setRightsDialog(role) {
      // 绑定当前角色的id
      this.currentAllotId = role.id
      // 获取所有权限列表
      const { data: res } = await this.$http.get('rights/tree')
      if (res.meta.status !== 200) {
        return this.$message.error('获取权限列表失败')
      }
      this.rightsList = res.data
      console.log(this.rightsList)
      this.getLeefId(role, this.defKeys)
      this.setRightsDialogVisible = true
    },
    // 递归获得所有三级权限id
    getLeefId(node, arr) {
      if (!node.children) {
        return arr.push(node.id)
      }
      node.children.forEach((item) => {
        this.getLeefId(item, arr)
      })
    },
    // 分配权限
    async allotRights() {
      const checkedRightsId = [
        ...this.$refs.allotRef.getCheckedKeys(),
        ...this.$refs.allotRef.getHalfCheckedKeys()
      ]
      const rids = checkedRightsId.join(',')
      const { data: res } = await this.$http.post(`roles/${this.currentAllotId}/rights`, { rids })
      if (res.meta.status !== 200) {
        return this.$message.error('分配角色权限失败')
      }
      this.$message.success('成功分配角色权限')
      this.getRolesList()
      this.setRightsDialogVisible = false
    },
    // 关闭分配权限弹窗后，将默认勾选列表清空
    setRightsDialogClosed() {
      this.defKeys = []
    }
  }
}
</script>

<style lang="less" scoped>
.el-tag {
  margin: 7px;
}
.bborder {
  border-bottom: 1px solid #ccc;
}
.tborder {
  border-top: 1px solid #ccc;
}
.vcenter {
  display: flex;
  align-items: center;
}
</style>
